//
//  LoanMainController.m
//  SecondLoan
//
//  Created by 姚永波 on 2019/8/18.
//  Copyright © 2019 姚永波. All rights reserved.
//

#import "LoanMainController.h"
#import "SDCycleScrollView.h"
#import "HomeBannerModel.h"
#import "PDWebViewController.h"
#import "MyLoanCell.h"
#import "CooperatorCell.h"
#import "LoginController.h"
#import "SLProductInfoViewController.h"
#import "SLMyLoanViewController.h"
#import "ProductModel.h"

#define BannerHeight ((SCREEN_WIDTH) * (150 / 375.0))
static CGFloat const tableSectionHeaderHeight = 50.0f;

@interface LoanMainController ()<UITableViewDelegate, UITableViewDataSource, SDCycleScrollViewDelegate>
@property (nonatomic, strong) SDCycleScrollView *homeScrollView;    //轮播图
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UITableView *tableView;
@property (strong, nonatomic) NSArray *bannerList;//banner列表
@property (assign,nonatomic) NSInteger cPage;
@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation LoanMainController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.title = @"借款";
    [self.view addSubview:self.tableView];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    [self loadData];
    self.bannerList = [HomeBannerModel mj_objectArrayWithKeyValuesArray:@[
                                                                          @{
                                                                              @"picture":@"loan_top_scroll1.jpg",
                                                                              
                                                                              },
                                                                          @{
                                                                              @"picture":@"loan_top_scroll2.jpg",
                                                                              @"jumpURL":@""
                                                                              },
                                                                          @{
                                                                              @"picture":@"loan_top_scroll3.jpg",
                                                                              @"jumpURL":@""
                                                                              }]];
    [self setupTopScrollViewWithImageURLArray];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    self.navigationBarBgView.backgroundColor = COLOR_ThemeRed;
    [self setNavigationTitle:@"借款" color:COLOR_White];
}

- (void)loadData
{
    self.cPage = 1;
    [self loadCurrentPageData];
}
- (void)loadMoreData
{
    [self loadCurrentPageData];
}
- (void)loadCurrentPageData
{
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:[UserLocal token] forKey:@"token"];
    [param setObject:@(self.cPage) forKey:@"pageNum"];
    [param setObject:@(20) forKey:@"pageSize"];
    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_home_product_list) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
        [self HUDdismiss];
        UITableView * tableView = self.tableView;
        NSDictionary *resultData = responseObject[@"data"];
        AUTO_TABLE_PLACEHOLDER(tableView,self.dataSource,resultData,error)
        if (!error) {
            NSArray * list = resultData[@"rows"];
            NSMutableArray * mlist = [NSMutableArray array];
            for (int i = 0; i< list.count; i ++) {
                ProductModel * data = [ProductModel mj_objectWithKeyValues:list[i]];
                [mlist addObject:data];
            }
            if (self.cPage == 1){
                self.dataSource = mlist;
            } else {
                self.dataSource =  [self.dataSource arrayByAddingObjectsFromArray:mlist];
            }
            self.cPage++;
            tableView.mj_footer.hidden = (self.dataSource.count >= [resultData[@"total"] integerValue]);
        } else {
            [self HUDshowErrorWithStatus:error.localizedDescription];
        }
        [tableView.mj_header endRefreshing];
        [tableView.mj_footer endRefreshing];
        [tableView reloadData];
    }];
}

#pragma mark ============= UITableViewDelegate ==========
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    if (section == 0) {
//        return 1;
//    }
    return self.dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//    if (section == 0) {
//        return 0;
//    }
    return tableSectionHeaderHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.section == 0) {
//        return 90;
//    }
    return [CooperatorCell cellHeight];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
//    if (section == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, tableSectionHeaderHeight)];
        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_table_sec_hint"]];
        imgView.frame = CGRectMake(10, 15, 7, tableSectionHeaderHeight - 2*15);
        [view addSubview:imgView];
        UILabel *lblRecommend = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imgView.frame) + 8, 0, 120, tableSectionHeaderHeight)];
        lblRecommend.text = @"贷款产品";
        lblRecommend.font = Font14Bold;
        lblRecommend.textColor = COLOR_BlackText_33;
        [view addSubview:lblRecommend];
        view.backgroundColor = [UIColor clearColor];
        
        UIButton *btnMore = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnMore addTarget:self action:@selector(goMyLoanAction) forControlEvents:UIControlEventTouchUpInside];
        [btnMore setTitle:@"我的贷款" forState:UIControlStateNormal];
        btnMore.titleLabel.textAlignment = NSTextAlignmentRight;
        [btnMore setFrame:CGRectMake(SCREEN_WIDTH - 100 , 0, 90, tableSectionHeaderHeight)];
        [btnMore setTitleColor:COLOR_Gary_99 forState:UIControlStateNormal];
        btnMore.titleLabel.font =  Font14;
        [view addSubview:btnMore];
        
        UIImageView *arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_right"]];
        CGFloat arrowHeight = arrow.bounds.size.height;
        CGFloat arrowWidth = arrow.bounds.size.width;
        arrow.frame = CGRectMake(SCREEN_WIDTH - arrow.bounds.size.width - 10, (tableSectionHeaderHeight - arrowHeight)/2.0, arrowWidth, arrowHeight);
        [view addSubview:arrow];
        return view;
//    }
//    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.section == 0) {
//        MyLoanCell *loanCell = [tableView dequeueReusableCellWithIdentifier:@"MyLoanCell"];
//        loanCell.selectionStyle = UITableViewCellSelectionStyleNone;
//        return loanCell;
//    }else{
        CooperatorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CooperatorCell"];
        if (cell == nil) {
            cell = [[CooperatorCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CooperatorCell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.dataSource[indexPath.row];
        return cell;
//    }
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SLProductInfoViewController *productInfo = [[SLProductInfoViewController alloc] init];
    ProductModel *model = self.dataSource[indexPath.row];
    productInfo.productId = model.productId;
    [self.navigationController pushViewController:productInfo animated:YES];
}

- (void)goMyLoanAction
{
    if (![UserLocal isLogin]) {
        MainNavigationController * vc = [[MainNavigationController alloc]initWithRootViewController:[[LoginController alloc] init]];
        [self presentViewController:vc animated:YES completion:nil];
        return;
    }else{
        SLMyLoanViewController *applyVC = [[SLMyLoanViewController alloc] init];
        [self.navigationController pushViewController:applyVC animated:YES];
    }
}
#pragma mark - ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ 循环滚动 ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
- (void)setupTopScrollViewWithImageURLArray {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //        _homeScrollView.placeholderImage = [UIImage imageNamed:@"default_fang"];
        NSMutableArray *imgBanners = [NSMutableArray new];
        [self.bannerList enumerateObjectsUsingBlock:^(HomeBannerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [imgBanners addObject:obj.picture];
//            [imgBanners addObject:@"loan_top_scroll"];
        }];
        self.homeScrollView.imageURLStringsGroup = imgBanners;
    });
    self.homeScrollView.delegate = self;
}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    HomeBannerModel *banner = self.bannerList[index];
    if (banner.jumpURL.length) {
        PDWebViewController * vc = [[PDWebViewController alloc] init];
        vc.webUrl =  banner.jumpURL;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma set---get
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, KStatusBarAndNavigationBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT - KTabbarHeight - KStatusBarAndNavigationBarHeight) style:UITableViewStylePlain];
        _tableView.tableHeaderView = self.topView;
        _tableView.scrollEnabled = YES;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = COLOR_Gary_FA;
        [_tableView registerNib:[UINib nibWithNibName:@"MyLoanCell" bundle:nil] forCellReuseIdentifier:@"MyLoanCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"CooperatorCell" bundle:nil] forCellReuseIdentifier:@"CooperatorCell"];
    }
    return  _tableView;
}
- (UIView *)topView{
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, BannerHeight)];
        [_topView addSubview:self.homeScrollView];
    }
    return _topView;
}
- (SDCycleScrollView *)homeScrollView
{
    if (!_homeScrollView) {
        _homeScrollView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH - 20, BannerHeight - 10)];
        [_homeScrollView setBannerImageViewContentMode:UIViewContentModeScaleToFill];
        _homeScrollView.pageControlDotSize = CGSizeMake(8, 8);
        _homeScrollView.autoScrollTimeInterval = 3.0;
        _homeScrollView.backgroundColor = [UIColor clearColor];
        _homeScrollView.pageDotColor = COLOR_Gary_99;
        _homeScrollView.currentPageDotColor = COLOR_ThemeRed;
    }
    return _homeScrollView;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

@end
